"""
Phase 2: Crisis Prediction — Do Demographics Signal Vulnerability?
==================================================================
LPM (PanelGLS) models testing whether demographic structure (Z factors,
youth dependency, old-age dependency) predicts banking/currency/sovereign
crisis onset, alongside standard early warning variables.
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)


def run_regression(df, y_var, x_vars, label, feature_names=None):
    """Run PanelGLS and return results dict."""
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  {label}: insufficient obs ({len(sub)}), skipping")
        return None

    gls = PanelGLS()
    y = sub[y_var].values
    X = sub[x_vars].values
    gls.fit(y, X, sub['iso3'].values, sub['year'].values)

    names = feature_names if feature_names else x_vars
    result = {
        'model': label,
        'n_obs': gls.n_obs,
        'n_countries': gls.n_countries,
        'r_squared': gls.r_squared,
        'rho': gls.rho,
    }
    for i, name in enumerate(names):
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f})")
    for i, name in enumerate(names):
        sig = stars(gls.pvalues[i])
        print(f"    {name:30s} {gls.beta[i]:8.4f} ({gls.se[i]:.4f}) {sig}")

    return result


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    """Format coefficient with stars and SE."""
    s = stars(p)
    return f"{val:.4f}{s}", f"({se:.4f})"


def write_prediction_table(results, filename, title):
    """Write regression results as markdown table."""
    if not results:
        return

    lines = [f"# {title}\n"]

    # Collect all variable names across results
    all_vars = []
    for r in results:
        for k in r:
            if k.endswith('_coef'):
                vname = k.replace('_coef', '')
                if vname not in all_vars:
                    all_vars.append(vname)

    # Header
    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    # Coefficient rows (two-row format: coef + se)
    for var in all_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    # Footer
    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    n_row = "| N |"
    r2_row = "| R² |"
    nc_row = "| Countries |"
    for r in results:
        n_row += f" {r['n_obs']} |"
        r2_row += f" {r['r_squared']:.4f} |"
        nc_row += f" {r['n_countries']} |"
    lines.append(n_row)
    lines.append(r2_row)
    lines.append(nc_row)

    lines.append("\n*Panel GLS with country and year fixed effects. "
                 "Standard errors in parentheses.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


def main():
    print("=" * 70)
    print("PHASE 2: CRISIS PREDICTION — DO DEMOGRAPHICS SIGNAL VULNERABILITY?")
    print("=" * 70)

    df = pd.read_csv(DATA / "crises_panel.csv")
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")
    print(f"Banking crisis onsets: {df['banking_crisis_onset'].sum():.0f}")
    print(f"Any crisis onsets: {df['any_crisis_onset'].sum():.0f}")

    eba_controls = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'rgdp_growth', 'kaopen']
    ew_controls = ['ca_gdp_lag1', 'fiscal_bal_gdp', 'reserves_to_liab',
                   'rgdp_growth', 'inflation', 'kaopen', 'nfa_gdp_lag']

    # ── Table 1: Banking Crisis Prediction ──
    print("\n" + "=" * 50)
    print("TABLE 1: BANKING CRISIS PREDICTION")
    print("=" * 50)

    results_banking = []

    # M1: Z → banking crisis onset (baseline)
    print("\n--- M1: Z → banking_crisis_onset ---")
    r = run_regression(df, 'banking_crisis_onset',
                       ['Z_1', 'Z_2', 'Z_3'] + eba_controls,
                       'M1: Z baseline')
    if r: results_banking.append(r)

    # M2: OADR specification
    print("\n--- M2: old_dep → banking_crisis_onset ---")
    r = run_regression(df, 'banking_crisis_onset',
                       ['old_dep'] + eba_controls,
                       'M2: OADR')
    if r: results_banking.append(r)

    # M3: Youth bulge (Doerr et al.)
    print("\n--- M3: youth_dep → banking_crisis_onset ---")
    r = run_regression(df, 'banking_crisis_onset',
                       ['youth_dep'] + eba_controls,
                       'M3: Youth')
    if r: results_banking.append(r)

    # M4: Z alongside standard early warning
    print("\n--- M4: Z + early warning vars ---")
    r = run_regression(df, 'banking_crisis_onset',
                       ['Z_1', 'Z_2', 'Z_3'] + ew_controls,
                       'M4: Z + EW')
    if r: results_banking.append(r)

    # M5: Early warning only (for incremental R² comparison)
    print("\n--- M5: Early warning only (no Z) ---")
    r = run_regression(df, 'banking_crisis_onset',
                       ew_controls,
                       'M5: EW only')
    if r: results_banking.append(r)

    # M6: Z × KAOPEN interaction
    print("\n--- M6: Z × KAOPEN interaction ---")
    interact_vars = ['Z_1', 'Z_2', 'Z_3', 'Z_1_x_kaopen', 'Z_2_x_kaopen', 'Z_3_x_kaopen']
    available = [v for v in interact_vars if v in df.columns]
    r = run_regression(df, 'banking_crisis_onset',
                       available + eba_controls,
                       'M6: Z×KAOPEN')
    if r: results_banking.append(r)

    write_prediction_table(results_banking, "crisis_prediction.md",
                           "Crisis Prediction: Banking Crisis Onset")

    # ── Table 2: Any Crisis + By Type ──
    print("\n" + "=" * 50)
    print("TABLE 2: CRISIS PREDICTION BY TYPE")
    print("=" * 50)

    results_type = []

    # Any crisis
    print("\n--- Any crisis onset ---")
    r = run_regression(df, 'any_crisis_onset',
                       ['Z_1', 'Z_2', 'Z_3'] + eba_controls,
                       'Any Crisis')
    if r: results_type.append(r)

    # Banking onset
    print("\n--- Banking crisis onset ---")
    r = run_regression(df, 'banking_crisis_onset',
                       ['Z_1', 'Z_2', 'Z_3'] + eba_controls,
                       'Banking')
    if r: results_type.append(r)

    # Currency onset
    print("\n--- Currency crisis onset ---")
    r = run_regression(df, 'currency_crisis_onset',
                       ['Z_1', 'Z_2', 'Z_3'] + eba_controls,
                       'Currency')
    if r: results_type.append(r)

    # Sovereign onset
    print("\n--- Sovereign crisis onset ---")
    r = run_regression(df, 'sovereign_crisis_onset',
                       ['Z_1', 'Z_2', 'Z_3'] + eba_controls,
                       'Sovereign')
    if r: results_type.append(r)

    write_prediction_table(results_type, "crisis_by_type.md",
                           "Crisis Prediction by Type")

    # ── Table 3: Incremental R² ──
    print("\n" + "=" * 50)
    print("TABLE 3: INCREMENTAL R² — DEMOGRAPHIC CONTRIBUTION")
    print("=" * 50)

    r2_lines = ["# Incremental R²: Demographic Contribution to Crisis Prediction\n"]
    r2_lines.append("| Dependent Variable | R² (EW only) | R² (EW + Z) | ΔR² | % Improvement |")
    r2_lines.append("|:---|---:|---:|---:|---:|")

    for dep_var, label in [('banking_crisis_onset', 'Banking Crisis Onset'),
                           ('any_crisis_onset', 'Any Crisis Onset'),
                           ('ca_reversal', 'CA Reversal (≥3pp)')]:
        # EW only
        r_ew = run_regression(df, dep_var, ew_controls, f'{label} EW-only')
        # EW + Z
        r_ewz = run_regression(df, dep_var,
                                ['Z_1', 'Z_2', 'Z_3'] + ew_controls,
                                f'{label} EW+Z')

        if r_ew and r_ewz:
            dr2 = r_ewz['r_squared'] - r_ew['r_squared']
            pct = (dr2 / r_ew['r_squared'] * 100) if r_ew['r_squared'] > 0 else 0
            r2_lines.append(f"| {label} | {r_ew['r_squared']:.4f} | "
                          f"{r_ewz['r_squared']:.4f} | {dr2:.4f} | {pct:.1f}% |")

    r2_lines.append("\n*ΔR² measures the additional explanatory power from adding Z₁, Z₂, Z₃ "
                    "to early warning models.*")

    path = OUT_TABLES / "incremental_r2.md"
    path.write_text('\n'.join(r2_lines))
    print(f"\n  Saved: {path}")

    print("\n" + "=" * 70)
    print("PHASE 2 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
